package com.atguigu.lease.web.admin.controller.login;


import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "后台管理系统登录管理")
@RestController
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    LoginService loginService;

    @Operation(summary = "获取图形验证码")
    @GetMapping("login/captcha")
    public Result<CaptchaVo> getCaptcha() {
        CaptchaVo vo = loginService.captcha();
        return Result.ok(vo);
    }

    @Operation(summary = "登录")
    @PostMapping("login")
    public Result<String> login(@RequestBody LoginVo loginVo) {
        String token = loginService.login(loginVo);
        return Result.ok(token);
    }

    //问题：拦截器目前只负责校验令牌，controller需要令牌的负载数据，还需要自己来解析，如果很多controller都需要负载数据，都来解析令牌，代码是重复的。
    //解决办法：让拦截器负载解析令牌，获取负载数据。然后通过ThreadLocal将数据绑定到线程上，当请求放行到controller，controller只需要从线程上获取数据即可。无需解析令牌。
/*    @Operation(summary = "获取登陆用户个人信息")
    @GetMapping("info")
    public Result<SystemUserInfoVo> info(@RequestHeader("access_token") String token) {
        Claims claims = JwtUtil.parseToken(token); //负载    {id:1,username:'admin'}
        Long userId = claims.get("userId", Long.class);
        //String username = claims.get("username", String.class);
        SystemUser systemUser = loginService.info(userId);

        SystemUserInfoVo vo = new SystemUserInfoVo();
        vo.setName(systemUser.getName()); //昵称
        vo.setAvatarUrl(systemUser.getAvatarUrl()); //头像
        return Result.ok(vo);
    }*/


    @Operation(summary = "获取登陆用户个人信息")
    @GetMapping("info")
    public Result<SystemUserInfoVo> info() {
        Long userId = LoginUserContext.getLoginUser().getUserId(); //从线程上获取数据
        SystemUser systemUser = loginService.info(userId);

        SystemUserInfoVo vo = new SystemUserInfoVo();
        vo.setName(systemUser.getName()); //昵称
        vo.setAvatarUrl(systemUser.getAvatarUrl()); //头像
        return Result.ok(vo);
    }
}